package com.wunu.zn.api.appliance.model;
import java.util.Calendar;
import java.util.Date;

import common.plugin.mybatis.Db;
import common.plugin.mybatis.Model;
import common.plugin.mybatis.Table;

/**
 * 
 * @author KinFeng
 *
 */
@Table("`t_wunu_app_captcha` ")
public class AppCaptcha extends Model<AppCaptcha>{
	
	public static final int MINUTE_TIME_OUT = 30;
	
	public static final int TYPE_REGIST = 1;
	public static final int TYPE_RESET_PASSWORD = 2;
	public static final int TYPE_BIND_PNHONE = 3;
	
	public static final int STATUS_USE_NO = 0;
	public static final int STATUS_USE_YES = 1;
	

	public static void add(String account, String captchaCode, int captchaType) 
	{
		AppCaptcha captcha = new AppCaptcha();
		
		Calendar cal = Calendar.getInstance();
		captcha.set("account", account)
			   .set("code", captchaCode)
			   .set("type", captchaType)
			   .set("createTime", cal.getTime());
		cal.add(Calendar.MINUTE, MINUTE_TIME_OUT);
		captcha.set("deadTime", cal.getTime());
		
		captcha.save();
	}


	public static boolean willUse(String account, String captcha) 
	{
		String sql = "select * from app_captcha where account = #{account} and code = #{captcha} order by createTime desc limit 1";
		AppCaptcha appCaptcha = Db.findFirst(AppCaptcha.class, sql, "account, captcha", account, captcha);
		if (appCaptcha != null && appCaptcha.isValid()) 
		{
			//标记为已用
			appCaptcha.set("status", STATUS_USE_YES);
			Db.update(appCaptcha);
			return true;
		}
		return false;
	}


	private boolean isValid() 
	{
		Date now = new Date();
		Date deadTime = getDate("deadTime");
		return getInt("status") == STATUS_USE_NO && now.before(deadTime);
	}

}
